package com.szqhyxj.youxiangju.biz.update;

import android.os.Environment;
import android.support.annotation.NonNull;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil {

    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;

    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
    }

    public void download1(final String url, File file, final OnDownloadListener listener) {
        RequestParams requestParams = new RequestParams(url);
        // 为RequestParams设置文件下载后的保存路径
        requestParams.setSaveFilePath(file.getPath());
        // 下载完成后自动为文件命名
        requestParams.setAutoRename(true);
        x.http().get(requestParams, new org.xutils.common.Callback.ProgressCallback<File>() {

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                int progress = (int) (current * 1.0f / total * 100);
                listener.onDownloading(progress);
            }

            @Override
            public void onSuccess(File result) {
                listener.onDownloadSuccess();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                listener.onDownloadFailed();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                listener.onDownloadFailed();
            }

            @Override
            public void onFinished() {

            }
        });
    }
        /**
         * @param url      下载连接
         * @param file     文件
         * @param listener 下载监听
         */
    public void download(final String url, File file, final OnDownloadListener listener) {

        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                listener.onDownloadFailed();
            }

            @Override
            public void onResponse(Call call, Response response) {
                byte[] buf = new byte[2048];
                int len = 0;
                // 储存下载文件的目录
                assert response.body() != null;
                long total = response.body().contentLength();
                assert response.body() != null;
                try (InputStream is = response.body().byteStream(); FileOutputStream fos = new FileOutputStream(file)) {
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess();
                } catch (Exception e) {
                    listener.onDownloadFailed();
                }
            }
        });
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        return downloadFile.getAbsolutePath();
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    @NonNull
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * @param progress 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed();
    }
}